import React, {useEffect, useState} from "react";
import {Button, Modal, Table, Tree} from "antd"
import axios from "axios";
import {DeleteOutlined, ExclamationCircleOutlined, UnorderedListOutlined} from "@ant-design/icons";

const {confirm} = Modal
export default function RoleList() {
    const [dataSource, setDataSource] = useState([])
    const [isModalVisible, setIsModalVisibel] = useState(false)
    // 树形组件权限列表
    const [rightList, setRightList] = useState([])
    // 当前权限
    const [currentRights, setCurrentRights] = useState([])
    const [currentId, setCurrentId] = useState(0)
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render: (id) => {
                return <b>{id}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: 'roleName'
        },
        {
            title: '操作',
            render: (item) => {
                return (
                    <div>
                        <Button type={"primary"} shape="circle" icon={<UnorderedListOutlined/>} onClick={() => {
                            setIsModalVisibel(true)
                            setCurrentRights(item.rights)
                            setCurrentId(item.id)
                        }}/>

                        <Button type={"danger"} shape="circle" style={{margin: 10}} icon={<DeleteOutlined/>}
                                onClick={() => confirmMethod(item)}/>

                    </div>
                )
            }
        }
    ]
    // 返回权限列表
    useEffect(async () => {
        let res = await axios.get('http://localhost:5000/roles')
        setDataSource(res.data)
    }, [])
    // 返回列表树
    useEffect(async () => {
        let res = await axios.get('http://localhost:5000/rights?_embed=children')
        setRightList(res.data)
    }, [])
    //确定是否删除弹框
    const confirmMethod = (item) => {
        confirm({
            title: '确定要删除吗',
            icon: <ExclamationCircleOutlined/>,
            // content: 'Some descriptions',
            async onOk() {
                // console.log('OK');
                await deleteMethod(item)
            },
            onCancel() {
                // console.log('Cancel');
            },
        });
    }

    // 删除函数
    const deleteMethod = async (item) => {
        console.log(item)
        if (item.grade === 1) {
            setDataSource(dataSource.filter(data => data.id !== item.id))
            await axios.delete(`http://localhost:5000/roles/${item.id}`)
        } else if (item.grade === 2) {
            let list = dataSource.filter(data => data.id === item.rightId)
            list[0].children = list[0].children.filter(data => data.id !== item.id)
            setDataSource([...dataSource])
        }
    }
    // 成功函数
    const handleOk = () => {
        setIsModalVisibel(false)
        // 同步datasource
        setDataSource(dataSource.map(item => {
            if (item.id === currentId) {
                return {
                    ...item,
                    rights: currentRights
                }
            }
            return item
        }))
        // patch
        axios.patch(`http://localhost:5000/roles/${currentId}`,{
            rights:currentRights
        })
    }
    // 取消函数
    const handleCancel = () => {
        setIsModalVisibel(false)
    }

    const onSelect = () => {
    }
    const onCheck = (checkKeys) => {
        setCurrentRights(checkKeys)
    }
    return (
        <div>
            {/* rowKey是用在后端返回数据没有key字段时，告诉Table组件重新寻找对应值作为key */}
            <Table dataSource={dataSource} columns={columns} rowKey={(item) => item.id}/>
            <Modal title="权限分配" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
                <Tree
                    checkable
                    checkedKeys={currentRights}
                    onSelect={onSelect}
                    onCheck={onCheck}
                    treeData={rightList}
                />
            </Modal>
        </div>
    )
}
